// pages/tools/yaohaojieguo/yaohaojieguo.js
const util = require("../../../utils/util");
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    model: 2, //0为未中签,1为中签,2为未查询,3为订阅提醒
    inputCode: '', //输入框绑定input
    fromSubscribe: 0, //标记是否从订阅通知页来,1为是,0为不是
    arr: [], //用来储存城市和申请编码url
    cityIndex: 0, //城市下标
    remainDay: 0, //剩余天数
    listData: [], //订阅记录列表
    hasSubscribed: false, //订阅记录中是否含有当前输入的城市和code
    navtop: 44,
    inputHeight: 30,
    fromShare: 0,
    arrCity:["杭州", "广州", "深圳", "天津", "海南", "北京"]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (opt) {
    //获取胶囊位置信息
    if (ks.getMenuButtonBoundingClientRect) {
      let menuButtonObject = ks.getMenuButtonBoundingClientRect();
      if (menuButtonObject)
        this.setData({
          navtop: menuButtonObject.top,
          inputHeight: menuButtonObject.height,
        })
    }
    this.setData({
      fromShare: opt.fromShare || 0
    })
    util.getUrl(app.globalData.url).then(e => {
      util.request("sub_message.php", {
        action: 'urls'
      }, "POST").then(e => {
        console.log(e)
        this.setData({
          arr: e.data
        }, () => {
          if (opt.city) {
            // let arrCity = []
            // this.data.arr.forEach(el => {
            //   arrCity.push(el.cityname)
            //   console.log(arrCity)
            // });
            // this.setData({arrCity}, () => {
            //   console.log(this.data.arrCity)
            // })


            const cityIndex = this.data.arr.findIndex((item) => {
              return item.cityname.includes(opt.city)
            })
            console.log(cityIndex)
            console.log(this.data.arr)
            this.setData({
              cityIndex
            })
          }
          this.getRecord()
          if (opt.fromSubscribe == 1) {
            this.setData({
              fromSubscribe: 1,
              inputCode: opt.code
            }, () => {
              this.search()
            })
          }
        })
      })
    })
    setTimeout(()=>{
      console.log(this.data.arr)
    },0)
  },
  // 获取次月订阅记录
  getRecord() {
    util.request("sub_message.php", {
      action: 'list',
      openid: ks.getStorageSync("openid"),
      name: "名单查询结果"
    }, "POST").then(e => {
      let listData = e.data ? e.data.map(item => {
        item.cancel = "取消订阅"
        return item
      }) : []
      this.setData({
        listData
      })
      // 如果列表没有元素,说明未订阅,如果有一个符合城市和code相等,那么说明订阅了
      this.data.listData.length == 0 ? this.setData({
        hasSubscribed: false
      }) : this.setData({
        hasSubscribed: this.data.listData.some(item => {
          return item.city == this.data.arr[this.data.cityIndex].cityname && item.code == this.data.inputCode
        })
      })
    })
  },
  // 取消订阅
  cancelSubscribe(e) {
    let code = util.getValue("code", e)
    let city = util.getValue("city", e)
    let data = {
      action: "del",
      openid: ks.getStorageSync('openid'),
      name: "名单查询结果",
      city,
      code
    }
    util.request("sub_message.php", data, "POST").then(e => {
      if (e.data.state == 1) {
        this.getRecord()
        ks.showToast({
          title: '取消订阅成功',
          icon: 'none',
          mask: true
        })
      }
    })
  },
  // 摇号日期提醒
  // getTime() {
  //   const nowDate = new Date().getDate()
  //   const nowYear = new Date().getFullYear()
  //   const nowMonth = new Date().getMonth() + 1
  //   // 如果小于26号,
  //   if (nowDate < 26) {
  //     this.setData({
  //       remainDay: 26 - nowDate,
  //       year: nowYear,
  //       month: nowMonth
  //     })
  //   } else {
  //     // 如果是12月,那么加一年,并且12月变成一月
  //     const nextMonth = nowMonth == 11 ? 1 : nowMonth + 1
  //     const nextYear = nowMonth == 11 ? nowYear + 1 : nowYear
  //     this.setData({
  //       remainDay: this.datedifference(`${nextYear}-${nextMonth}-26`, `${nowYear}-${nowMonth}-${nowDate}`),
  //       year: nextYear,
  //       month: nextMonth
  //     })
  //   }
  // },
  // //sDate1和sDate2是2006-12-18格式  
  // //计算两个时间差了多少天
  // datedifference(sDate1, sDate2) {
  //   var dateSpan,
  //     tempDate,
  //     iDays;
  //   sDate1 = Date.parse(sDate1);
  //   sDate2 = Date.parse(sDate2);
  //   dateSpan = sDate2 - sDate1;
  //   dateSpan = Math.abs(dateSpan);
  //   iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
  //   return iDays
  // },
  // 修改城市
  changeCity(e) {
    this.setData({
      cityIndex: e.detail.value
    })
    this.getRecord()
  },
  // 复制url
  copyUrl(e) {
    const url = util.getValue("url", e)
    // const tit = '因为小程序规定不能打开链接，所以请将链接复制并粘贴到浏览器打开。'
    const tit = '提示'
    const content = url
    ks.showModal({
      title: tit,
      content: '因为小程序规定不能打开链接，所以请将链接复制并粘贴到浏览器打开。\n\n' + content,
      cancelText: '关闭弹窗',
      confirmText: '复制网址',
      success: (res) => {
        if (res.confirm) {
          ks.setClipboardData({
            data: url,
            success: (res) => {
              ks.showToast({
                title: '复制成功',
              })
            }
          })
        }
      },
    })
  },
  // 前往次月订阅提醒
  goSub() {
    var regEx = new RegExp("[^a-zA-Z0-9\_\u4e00-\u9fa5]", "i")
    if ((!regEx.test(this.data.inputCode.trim()) && this.data.inputCode.trim().length == 13) || this.data.listData.length != 0) {
      this.setData({
        model: 3
      })
      this.getRecord()
    } else {

      ks.showToast({
        title: '请输入正确的13位申请编码后再订阅',
        icon: 'none',
        mask: true
      })
    }

  },
  // 订阅成功
  subsuccess() {
    this.getRecord()
    ks.showToast({
      title: '订阅成功，待结果公布后会有提醒',
      icon: 'none',
      mask: 'true'
    })
  },
  // 输入框绑定input
  input(e) {
    this.setData({
      inputCode: e.detail.value
    })
  },
  //查询
  search() {
    var regEx = new RegExp("[^a-zA-Z0-9\_\u4e00-\u9fa5]", "i")
    if (!regEx.test(this.data.inputCode.trim()) && this.data.inputCode.trim().length == 13) {
      util.request("sub_message.php", {
        action: "search",
        code: this.data.inputCode,
        city: this.data.arr[this.data.cityIndex].cityname
      }, "POST").then(e => {
        const state = e.data ? e.data.state : ''
        //0为未中签,1为中签
        if (state == 0 || state == 1) {
          this.setData({
            model: state,
          })
        }
      })
    } else {
      ks.showToast({
        title: '请输入正确的13位申请编码后再查询',
        icon: 'none'
      })
    }
  },
  // 重置编码
  reset() {
    this.setData({
      model: 2
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '车牌摇号结果查询',
      path: `pages/tools/yaohaojieguo/yaohaojieguo?city=${this.data.arr[this.data.cityIndex].cityname}&fromShare=1`
    }
  }
})